package com.nku.mason.masonframework.core.tools;

import java.lang.reflect.Field;
import java.util.Map;

import com.nku.mason.masonframework.core.annotations.Inject;
import com.nku.mason.masonframework.util.ArrayUtil;
import com.nku.mason.masonframework.util.CollectionUtil;
import com.nku.mason.masonframework.util.ReflectionUtil;
/**
 * 通过BeanTool获取所有BeanMap
 * @author Mason
 * @date 2017年3月13日
 */
public final class IOCTool {
	
	static {
		Map<Class<?>, Object> beanMap = BeanTool.getBeanMap();
		if (!CollectionUtil.isEmpty(beanMap)) {
			//遍历BeanMap
			for(Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()){
				//从BeanMap中获取Bean类与Bean实例
				Class<?> beanClass = beanEntry.getKey();
				Object beanInstance = beanEntry.getValue();
				//获取Bean类定义的所有成员变量(简称Bean Field)
				Field[] beanFields = beanClass.getDeclaredFields();
				if (!ArrayUtil.isEmpty(beanFields)) {
					//遍历BeanField
					for(Field beanField : beanFields){
						//判断当前BeanField是否带有Inject注解
						if (beanField.isAnnotationPresent(Inject.class)) {
							//在BeanMap中获取BeanField对应的实例
							Class<?> beanFieldClass = beanField.getType();
							Object beanFieldInstance = beanMap.get(beanFieldClass);
							if (beanFieldInstance != null) {
								//通过反射初始化BeanField的值
								ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
							}
						}
					}
				}
			}
		}
	}
}
